import { post, apiPaths } from '../../utils/request.js'

Page({
  data: {
    timeRange: 'week',
    overviewData: {
      projects: { total: 0, in_progress: 0, archived: 0 },
      tasks: { total: 0, completed: 0, in_progress: 0 },
      users: { total: 0 }
    },
    projectProgress: [],
    startDate: '',
    endDate: '',
    today: '',
    projectStats: {
      total: 0,
      inProgress: 0,
      archived: 0
    },
    taskStats: {
      total: 0,
      completed: 0,
      inProgress: 0
    },
    memberStats: {
      total: 0
    },
    completionRate: 0,
    keyMetrics: {
      avgProjectDuration: 0,
      avgTaskCompletionTime: 0,
      highPriorityCompletionRate: 0,
      teamEfficiencyIndex: 0
    },
    memberTaskStats: []
  },

  onLoad() {
    // 初始化日期
    const now = new Date()
    const today = now.toISOString().split('T')[0]
    const lastWeek = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
    
    this.setData({
      today: today,
      startDate: lastWeek,
      endDate: today
    })
    
    this.loadStatistics()
    this.loadProjectProgress()
    
    // 设置假数据用于测试
    this.setMockData()
  },
  
  setMockData() {
    // 设置关键指标假数据
    this.setData({
      keyMetrics: {
        avgProjectDuration: 15,
        avgTaskCompletionTime: 3.5,
        highPriorityCompletionRate: 85,
        teamEfficiencyIndex: 78
      },
      memberTaskStats: [
        { id: 1, name: '张三', role: '项目经理', assigned: 12, completed: 10, completionRate: 83 },
        { id: 2, name: '李四', role: '开发工程师', assigned: 18, completed: 15, completionRate: 83 },
        { id: 3, name: '王五', role: '测试工程师', assigned: 8, completed: 7, completionRate: 88 }
      ]
    })
    
    // 绘制其他图表
    this.drawTaskPriorityChart()
    this.drawTaskCompletionChart()
    this.drawTeamEfficiencyChart()
    this.drawProjectHealthChart()
  },
  
  drawTaskPriorityChart() {
    // 任务优先级分布图表（假数据）
    const ctx = wx.createCanvasContext('taskPriorityChart')
    
    // 绘制饼图
    const centerX = 150
    const centerY = 100
    const radius = 60
    
    const priorities = [
      { name: '紧急', value: 15, color: '#FF3B30' },
      { name: '高', value: 25, color: '#FF9500' },
      { name: '中', value: 40, color: '#007AFF' },
      { name: '低', value: 20, color: '#34C759' }
    ]
    
    let startAngle = 0
    const total = priorities.reduce((sum, item) => sum + item.value, 0)
    
    priorities.forEach(item => {
      const angle = (item.value / total) * 2 * Math.PI
      
      // 绘制扇形
      ctx.beginPath()
      ctx.moveTo(centerX, centerY)
      ctx.arc(centerX, centerY, radius, startAngle, startAngle + angle)
      ctx.closePath()
      ctx.setFillStyle(item.color)
      ctx.fill()
      
      // 绘制标签
      const labelAngle = startAngle + angle / 2
      const labelX = centerX + (radius + 30) * Math.cos(labelAngle)
      const labelY = centerY + (radius + 30) * Math.sin(labelAngle)
      
      ctx.setFillStyle('#333')
      ctx.setFontSize(12)
      ctx.setTextAlign('center')
      ctx.fillText(item.name, labelX, labelY)
      
      startAngle += angle
    })
    
    ctx.draw()
  },
  
  drawTaskCompletionChart() {
    // 任务完成趋势图表（假数据）
    const ctx = wx.createCanvasContext('taskCompletionChart')
    
    // 绘制折线图
    const data = [10, 15, 12, 18, 22, 20, 25]
    const labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    
    const width = 300
    const height = 200
    const padding = 30
    
    // 绘制坐标轴
    ctx.setStrokeStyle('#ccc')
    ctx.setLineWidth(1)
    ctx.moveTo(padding, padding)
    ctx.lineTo(padding, height - padding)
    ctx.lineTo(width - padding, height - padding)
    ctx.stroke()
    
    // 绘制折线
    ctx.setStrokeStyle('#007AFF')
    ctx.setLineWidth(2)
    ctx.beginPath()
    
    const maxValue = Math.max(...data)
    
    data.forEach((value, index) => {
      const x = padding + (index * (width - 2 * padding) / (data.length - 1))
      const y = height - padding - (value / maxValue) * (height - 2 * padding)
      
      if (index === 0) {
        ctx.moveTo(x, y)
      } else {
        ctx.lineTo(x, y)
      }
      
      // 绘制数据点
      ctx.setFillStyle('#007AFF')
      ctx.beginPath()
      ctx.arc(x, y, 3, 0, 2 * Math.PI)
      ctx.fill()
    })
    
    ctx.stroke()
    
    // 绘制标签
    ctx.setFillStyle('#666')
    ctx.setFontSize(10)
    ctx.setTextAlign('center')
    
    labels.forEach((label, index) => {
      const x = padding + (index * (width - 2 * padding) / (labels.length - 1))
      ctx.fillText(label, x, height - padding + 20)
    })
    
    ctx.draw()
  },
  
  drawTeamEfficiencyChart() {
    // 团队效能分析图表（假数据）
    const ctx = wx.createCanvasContext('teamEfficiencyChart')
    
    // 绘制雷达图
    const centerX = 150
    const centerY = 100
    const radius = 80
    
    const metrics = [
      { name: '任务完成率', value: 85 },
      { name: '响应速度', value: 78 },
      { name: '协作能力', value: 92 },
      { name: '创新能力', value: 70 },
      { name: '学习能力', value: 88 }
    ]
    
    const numMetrics = metrics.length
    
    // 绘制网格
    ctx.setStrokeStyle('#eee')
    ctx.setLineWidth(1)
    
    for (let i = 1; i <= 5; i++) {
      const r = (radius * i) / 5
      ctx.beginPath()
      for (let j = 0; j < numMetrics; j++) {
        const angle = (j * 2 * Math.PI) / numMetrics - Math.PI / 2
        const x = centerX + r * Math.cos(angle)
        const y = centerY + r * Math.sin(angle)
        
        if (j === 0) {
          ctx.moveTo(x, y)
        } else {
          ctx.lineTo(x, y)
        }
      }
      ctx.closePath()
      ctx.stroke()
    }
    
    // 绘制轴线
    ctx.setStrokeStyle('#ccc')
    metrics.forEach((_, index) => {
      const angle = (index * 2 * Math.PI) / numMetrics - Math.PI / 2
      const x = centerX + radius * Math.cos(angle)
      const y = centerY + radius * Math.sin(angle)
      
      ctx.beginPath()
      ctx.moveTo(centerX, centerY)
      ctx.lineTo(x, y)
      ctx.stroke()
    })
    
    // 绘制数据
    ctx.setStrokeStyle('#007AFF')
    ctx.setFillStyle('rgba(0, 122, 255, 0.3)')
    ctx.setLineWidth(2)
    
    ctx.beginPath()
    metrics.forEach((metric, index) => {
      const value = metric.value / 100
      const angle = (index * 2 * Math.PI) / numMetrics - Math.PI / 2
      const r = radius * value
      const x = centerX + r * Math.cos(angle)
      const y = centerY + r * Math.sin(angle)
      
      if (index === 0) {
        ctx.moveTo(x, y)
      } else {
        ctx.lineTo(x, y)
      }
    })
    ctx.closePath()
    ctx.fill()
    ctx.stroke()
    
    // 绘制标签
    ctx.setFillStyle('#333')
    ctx.setFontSize(10)
    ctx.setTextAlign('center')
    
    metrics.forEach((metric, index) => {
      const angle = (index * 2 * Math.PI) / numMetrics - Math.PI / 2
      const r = radius + 20
      const x = centerX + r * Math.cos(angle)
      const y = centerY + r * Math.sin(angle)
      
      ctx.fillText(metric.name, x, y)
    })
    
    ctx.draw()
  },
  
  drawProjectHealthChart() {
    // 项目健康度雷达图（假数据）
    const ctx = wx.createCanvasContext('projectHealthChart')
    
    // 绘制雷达图
    const centerX = 150
    const centerY = 100
    const radius = 80
    
    const metrics = [
      { name: '进度', value: 80 },
      { name: '质量', value: 75 },
      { name: '风险', value: 60 },
      { name: '资源', value: 85 },
      { name: '沟通', value: 90 }
    ]
    
    const numMetrics = metrics.length
    
    // 绘制网格
    ctx.setStrokeStyle('#eee')
    ctx.setLineWidth(1)
    
    for (let i = 1; i <= 5; i++) {
      const r = (radius * i) / 5
      ctx.beginPath()
      for (let j = 0; j < numMetrics; j++) {
        const angle = (j * 2 * Math.PI) / numMetrics - Math.PI / 2
        const x = centerX + r * Math.cos(angle)
        const y = centerY + r * Math.sin(angle)
        
        if (j === 0) {
          ctx.moveTo(x, y)
        } else {
          ctx.lineTo(x, y)
        }
      }
      ctx.closePath()
      ctx.stroke()
    }
    
    // 绘制轴线
    ctx.setStrokeStyle('#ccc')
    metrics.forEach((_, index) => {
      const angle = (index * 2 * Math.PI) / numMetrics - Math.PI / 2
      const x = centerX + radius * Math.cos(angle)
      const y = centerY + radius * Math.sin(angle)
      
      ctx.beginPath()
      ctx.moveTo(centerX, centerY)
      ctx.lineTo(x, y)
      ctx.stroke()
    })
    
    // 绘制数据
    ctx.setStrokeStyle('#34C759')
    ctx.setFillStyle('rgba(52, 199, 89, 0.3)')
    ctx.setLineWidth(2)
    
    ctx.beginPath()
    metrics.forEach((metric, index) => {
      const value = metric.value / 100
      const angle = (index * 2 * Math.PI) / numMetrics - Math.PI / 2
      const r = radius * value
      const x = centerX + r * Math.cos(angle)
      const y = centerY + r * Math.sin(angle)
      
      if (index === 0) {
        ctx.moveTo(x, y)
      } else {
        ctx.lineTo(x, y)
      }
    })
    ctx.closePath()
    ctx.fill()
    ctx.stroke()
    
    // 绘制标签
    ctx.setFillStyle('#333')
    ctx.setFontSize(10)
    ctx.setTextAlign('center')
    
    metrics.forEach((metric, index) => {
      const angle = (index * 2 * Math.PI) / numMetrics - Math.PI / 2
      const r = radius + 20
      const x = centerX + r * Math.cos(angle)
      const y = centerY + r * Math.sin(angle)
      
      ctx.fillText(metric.name, x, y)
    })
    
    ctx.draw()
  },

  onTimeRangeChange(e) {
    const range = e.currentTarget.dataset.range
    this.setData({
      timeRange: range
    })
    // 重新加载数据
    this.loadStatistics()
    this.loadProjectProgress()
  },
  
  onStartDateChange(e) {
    this.setData({
      startDate: e.detail.value
    })
    // 重新加载数据
    this.loadStatistics()
    this.loadProjectProgress()
  },
  
  onEndDateChange(e) {
    this.setData({
      endDate: e.detail.value
    })
    // 重新加载数据
    this.loadStatistics()
    this.loadProjectProgress()
  },

  loadStatistics() {
    // 调用获取统计概览接口
    post(apiPaths.getStatistics).then(res => {
      console.log('Statistics data:', res);
      if (res.code === 200) {
        const data = res.data;
        
        // 更新概览数据
        this.setData({
          overviewData: data,
          // 更新页面中使用的数据
          projectStats: {
            total: data.projects.total || 0,
            inProgress: data.projects.in_progress || 0,
            archived: data.projects.archived || 0
          },
          taskStats: {
            total: data.tasks.total || 0,
            completed: data.tasks.completed || 0,
            inProgress: data.tasks.in_progress || 0
          },
          memberStats: {
            total: data.users.total || 0
          },
          // 计算完成率
          completionRate: data.tasks.total > 0 ? 
            Math.round((data.tasks.completed / data.tasks.total) * 100) : 0
        })
      } else {
        wx.showToast({
          title: res.message || '获取统计概览失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('Statistics error:', err);
      wx.showToast({
        title: err.message || '获取统计概览失败',
        icon: 'none'
      })
    })
  },

  loadProjectProgress() {
    // 调用获取项目进度统计接口
    post(apiPaths.getProjectProgress).then(res => {
      console.log('Project progress data:', res);
      if (res.code === 200) {
        // 转换数据格式以匹配页面需求
        const projectProgress = res.data.map(item => ({
          name: item.name,
          totalTasks: item.totalTasks,
          completedTasks: item.completedTasks,
          progress: parseFloat(item.progress.toFixed(2))
        }));
        
        this.setData({
          projectProgress: projectProgress
        })
        
        // 绘制图表
        this.drawProjectStatusChart()
      } else {
        wx.showToast({
          title: res.message || '获取项目进度统计失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('Project progress error:', err);
      wx.showToast({
        title: err.message || '获取项目进度统计失败',
        icon: 'none'
      })
    })
  },

  drawProjectStatusChart() {
    const projectProgress = this.data.projectProgress
    
    if (projectProgress.length === 0) return
    
    // 获取canvas上下文
    const ctx = wx.createCanvasContext('projectStatusChart')
    
    // 设置图表参数
    const canvasWidth = 300
    const canvasHeight = 200
    const barWidth = Math.min(30, (canvasWidth - 40) / Math.max(1, projectProgress.length) - 10)
    const barSpacing = Math.min(20, (canvasWidth - 40 - (barWidth * projectProgress.length)) / Math.max(1, projectProgress.length - 1))
    const maxProgress = 100
    
    // 绘制柱状图
    projectProgress.forEach((project, index) => {
      const x = index * (barWidth + barSpacing) + 20
      const barHeight = (project.progress / maxProgress) * (canvasHeight - 50)
      const y = canvasHeight - barHeight - 30
      
      // 绘制柱子
      ctx.setFillStyle('#007AFF')
      ctx.fillRect(x, y, barWidth, barHeight)
      
      // 绘制项目名称（截断过长的名称）
      ctx.setFillStyle('#333')
      ctx.setFontSize(12)
      ctx.setTextAlign('center')
      const projectName = project.name.length > 6 ? project.name.substring(0, 6) + '...' : project.name
      ctx.fillText(projectName, x + barWidth/2, canvasHeight - 10)
      
      // 绘制进度百分比
      ctx.setFillStyle('#666')
      ctx.setFontSize(10)
      ctx.fillText(project.progress + '%', x + barWidth/2, y - 5)
    })
    
    // 绘制图表
    ctx.draw()
  }
})